package qdu.rg012.ch4_data_file;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestIO extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ly_testio);


        findViewById(R.id.btn_createfile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String filename = null, filecontent = "";
                FileOutputStream fos = null;
                if(
                        (filename = ((EditText)findViewById(R.id.et_fn)).getEditableText().toString()).hashCode() == 0
                )    filename = "default.txt";
                else if("".equals(filename.trim()))
                    filename = "default.txt";

                if(
                        (filecontent = ((EditText)findViewById(R.id.et_fc)).getEditableText().toString()).hashCode() == 0
                )    filecontent = "";

                try {
                    fos = openFileOutput(filename, MODE_PRIVATE);
                    fos.write(filecontent.getBytes());

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                    if(fos != null) {
                        try {
                            fos.flush();
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        fos = null;
                    }
                }
            }
        });
    }
}
